package com.jsbj.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jsbj.base.Constants;
import com.jsbj.base.ResultBean;
import com.jsbj.enums.ConfigDictTypeEnum;
import com.jsbj.page.PageDomain;
import com.jsbj.page.TableSupport;
import com.jsbj.tools.BeanUtils;
import com.jsbj.tools.DateUtils;
import com.jsbj.tools.RequestHeaderUtils;
import com.jsbj.tools.StringUtils;
import com.jsbj.user.entities.*;
import com.jsbj.user.mapper.SysTenantMapper;
import com.jsbj.user.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 系统租户表 服务实现类
 * </p>
 *
 * @author jsbj
 * @since 2022-02-22
 */
@Service
public class SysTenantServiceImpl extends ServiceImpl<SysTenantMapper, SysTenant> implements ISysTenantService {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private ISysProjectService sysProjectService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    @Autowired
    private ISysTenantPermissionService sysTenantPermissionService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysOrgService sysOrgService;

    @Autowired
    private ISysFileService sysFileService;

    @Autowired
    private ISysRoleService sysRoleService;

    @Autowired
    private ISysRoleTenantService sysRoleTenantService;

    @Autowired
    private ISysRoleOrgService sysRoleOrgService;

    @Autowired
    private ISysRoleUserService sysRoleUserService;

    @Autowired
    private ISysSystemService sysSystemService;

    @Override
    public List<SysTenant> getByUserId(String userId) {
        System.out.println("intogetByUserId:-------------");
        List<SysTenant> ret = new ArrayList<>();
        List<SysTenant> list = baseMapper.getByUserId(userId);

        // 构建树
        // 先查出所有的一级节点（没有父节点的都是）
        List<SysTenant> parentList = new ArrayList<>();
        for (SysTenant temp : list) {
            String tenantCode = temp.getTenantCode();
            SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(tenantCode);
            if(null != sysProject){
                temp.setProId(sysProject.getId());
            }
            if (StringUtils.isEmpty(temp.getParentTenantCode())) {
                parentList.add(temp);
            } else {
                boolean flag = true;
                for (SysTenant temp1 : list) {
                    if (temp.getParentTenantCode().equals(temp1.getTenantCode())) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    parentList.add(temp);
                }
            }
        }
        for (SysTenant temp : parentList) {
            List<SysTenant> childs = getAllChildTenant(temp, list);
            temp.setChild(childs);
            ret.add(temp);
        }
        System.out.println("outgetByUserId:-------------"+ret);
        return ret;
    }

    private List<SysTenant> getAllChildTenant(SysTenant temp, List<SysTenant> list) {
        List<SysTenant> childList = new ArrayList<>();
        for (SysTenant child : list) {
            if (temp.getTenantCode().equals(child.getParentTenantCode())) {
                List<SysTenant> childs = getAllChildTenant(child, list);
                if (!CollectionUtils.isEmpty(childs)) {
                    child.setChild(childs);
                }
                childList.add(child);
            }
        }
        return childList;
    }


    @Override
    public List<String> getChildTenantCode(String tenantCode) {
        List<SysTenant> ret = new ArrayList<>();
        getAllChildTenantCode(tenantCode, ret);
        List<String> ls = new ArrayList<>();
        ls.add(tenantCode);
        for (SysTenant child : ret) {
            ls.add(child.getTenantCode());
        }
        return ls;
    }

    @Override
    public SysTenant getByTenantCode(String tenantCode) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled, 0);
        queryWrapper.eq(SysTenant::getTenantCode, tenantCode);
        queryWrapper.last(" limit 1");
        return baseMapper.selectOne(queryWrapper);
    }

    private List<SysTenant> getAllChildTenantCode(String tenantCode, List<SysTenant> ret) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getParentTenantCode, tenantCode);
        queryWrapper.eq(SysTenant::getDisabled,0);
        List<SysTenant> childs = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(childs)) {
            ret.addAll(childs);
            for (SysTenant child : childs) {
                this.getAllChildTenantCode(child.getTenantCode(), ret);
            }
        }
        return ret;
    }

    @Override
    public List<SysTenant> getByTenantTypeValue(String tenantTypeValue) {
        LambdaQueryWrapper<SysTenant> qw = new LambdaQueryWrapper<>();
        qw.eq(SysTenant::getTenantTypeValue,tenantTypeValue);
        qw.eq(SysTenant::getDisabled,0);
        qw.eq(SysTenant::getTenantTypeKey,"tenantType");
        return baseMapper.selectList(qw);
    }

    @Override
    public IPage<SysTenant> getListData(String inParam) {
        // 如果时候超级管理员，查所有，否则，只查询自己有权限的租户
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = sysUserService.getById(userId);

        JSONObject object = JSONObject.parseObject(inParam);
        String tenantName = object.getString("tenantName");
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled,0);
        // 如果租户名称是空的，查树，否则，查列表
        if (StringUtils.isEmpty(tenantName)) {
//            if ("0".equals(sysUser.getIsStatus())) {
//                queryWrapper.isNull(SysTenant::getParentTenantCode);
//            }
        } else {
            queryWrapper.like(SysTenant::getTenantName, tenantName);
        }
//        queryWrapper.orderByDesc(SysTenant::getCreateTime);
        List<String> tenantCodeLs = new ArrayList<>();
        // 只查询有权限的租户或者是自己创建的租户

//        if ("0".equals(sysUser.getIsStatus())) {
            // 查询有权限的租户
            tenantCodeLs = baseMapper.selectQXTenantCodeAndCreate(userId);
            List<String> finalTenantCodeLs = tenantCodeLs;
            queryWrapper.and((wrapper)->{
                wrapper.notIn(SysTenant::getParentTenantCode, finalTenantCodeLs).or().isNull(SysTenant::getParentTenantCode);
            });
            queryWrapper.in(SysTenant::getTenantCode, tenantCodeLs);
//            List<String> finalTenantCodeLs1 = tenantCodeLs;
//            queryWrapper.and(wq->wq.in(SysTenant::getTenantCode, finalTenantCodeLs1).or().eq(SysTenant::getCreaterId, userId));
//        }

        queryWrapper.orderByAsc(SysTenant::getSort);
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<SysTenant> page = new Page<>(pageNum, pageSize);
        IPage<SysTenant> iPage = baseMapper.selectPage(page, queryWrapper);
        for (SysTenant sysTenant : iPage.getRecords()) {
            if (StringUtils.isNotEmpty(sysTenant.getTenantTypeValue())) {
                sysTenant.setTenantTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.TENANTTYPE.getCode(), sysTenant.getTenantTypeValue()));
            }
            List<SysTenant> child = getChildren(sysTenant.getTenantCode(), sysUser.getIsStatus(), tenantCodeLs);
            if (CollectionUtils.isEmpty(child)) {
                sysTenant.setDel(true);
            } else {
                sysTenant.setDel(false);
                if (StringUtils.isEmpty(tenantName)) {
                    sysTenant.setChild(child);
                }
            }
            if (StringUtils.isNotEmpty(sysTenant.getTenantSuperAccount())) {
                sysTenant.setTenantSuperAccountDesc(sysUserService.getById(sysTenant.getTenantSuperAccount()).getUserName());
            }
            sysTenant.setUpdateTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, sysTenant.getUpdateTime()));
        }
        return iPage;
    }

    private List<SysTenant> getChildren(String tenantCode, String isStatus, List<String> tenantCodeLs) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled,0);
        queryWrapper.eq(SysTenant::getParentTenantCode, tenantCode);
        if (!"0".equals(isStatus)) {
            // 查询有权限的租户
            queryWrapper.in(SysTenant::getTenantCode, tenantCodeLs);
        }
        queryWrapper.orderByAsc(SysTenant::getSort);
        List<SysTenant> child = baseMapper.selectList(queryWrapper);
        for (SysTenant sysTenant : child) {
            List<SysTenant> child1 = getChildren(sysTenant.getTenantCode(), isStatus, tenantCodeLs);
            if (CollectionUtils.isEmpty(child1)) {
                sysTenant.setDel(true);
            } else {
                sysTenant.setDel(false);
                sysTenant.setChild(child1);
            }
        }
        return child;
    }

    @Override
    public ResultBean<JSONObject> saveOrUpdateData(SysTenant sysTenant) {
        // 校验必填
        if (StringUtils.isEmpty(sysTenant.getTenantCode()) || StringUtils.isEmpty(sysTenant.getTenantName()) || StringUtils.isEmpty(sysTenant.getTenantTypeValue())) {
            return new ResultBean<>().build("必填项不能为空！");
        }
        sysTenant.setTenantTypeKey(ConfigDictTypeEnum.TENANTTYPE.getCode());
        // 如果是项目类型，增加校验
        if ("3".equals(sysTenant.getTenantTypeValue())) {
            if (null == sysTenant.getSysProject() || StringUtils.isEmpty(sysTenant.getSysProject().getProCode()) || StringUtils.isEmpty(sysTenant.getSysProject().getProName())
                    || null == sysTenant.getSysProject().getProvinceCode() || StringUtils.isEmpty(sysTenant.getSysProject().getStartDateStr())
                    || StringUtils.isEmpty(sysTenant.getSysProject().getEndDateStr()) || null == sysTenant.getSysProject().getProType()
                    || null == sysTenant.getSysProject().getEngType() || null == sysTenant.getSysProject().getRoadKm()
                    || null == sysTenant.getSysProject().getRoadMoney() || StringUtils.isEmpty(sysTenant.getSysProject().getGeox())
                    || StringUtils.isEmpty(sysTenant.getSysProject().getGeoy()) || StringUtils.isEmpty(sysTenant.getSysProject().getIncludeSystem())) {
                return new ResultBean<>().build("项目信息必填项不能为空！");
            }
        }
        // 时间转换
        sysTenant.getSysProject().setStartDate(DateUtils.parseDate(sysTenant.getSysProject().getStartDateStr()));
        sysTenant.getSysProject().setEndDate(DateUtils.parseDate(sysTenant.getSysProject().getEndDateStr()));

        // 校验租户编码、租户名称和项目编码是否重复
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled, 0);
        if (StringUtils.isNotEmpty(sysTenant.getId())) {
            queryWrapper.ne(SysTenant::getId, sysTenant.getId());
        }
        queryWrapper.eq(SysTenant::getTenantCode,sysTenant.getTenantCode());
//        queryWrapper.and((wrapper)->{
//            wrapper.eq(SysTenant::getTenantCode,sysTenant.getTenantCode())
//                    .or().eq(SysTenant::getTenantName,sysTenant.getTenantName());});
        List<SysTenant> sysTenants = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(sysTenants)) {
            return new ResultBean<>().build("租户编码已存在，请重新填写！");
        }
        if ("3".equals(sysTenant.getTenantTypeValue())) {
            List<SysProject> sysProjects = sysProjectService.checkExist(sysTenant.getSysProject().getProCode()
                    , sysTenant.getSysProject().getProName(), sysTenant.getSysProject().getId());
            if (!CollectionUtils.isEmpty(sysProjects)) {
                return new ResultBean<>().build("项目编码已存在，请重新填写！");
            }
        }
        // 校验完毕，开始处理数据
        String userId = RequestHeaderUtils.getUserId(request);
        if (StringUtils.isEmpty(sysTenant.getId())) {
            sysTenant.setCreaterId(userId);
            sysTenant.setUpdateId(userId);
            baseMapper.insert(sysTenant);
        } else {
            SysTenant updateInfo = baseMapper.selectById(sysTenant.getId());
            BeanUtils.copyPropertiesIgnoreNull(sysTenant, updateInfo);
            updateInfo.setUpdateId(userId);
            updateInfo.setUpdateTime(new Date());
            baseMapper.updateById(updateInfo);
        }
        // 处理项目表
        if ("3".equals(sysTenant.getTenantTypeValue())) {
            boolean zhgdCreateTable = true;

            List<String> addSystemCode = new ArrayList<>();
            SysProject sysProject = sysTenant.getSysProject();
            sysProject.setTenantCode(sysTenant.getTenantCode());
            if (StringUtils.isEmpty(sysProject.getId())) {
                // 保存
                sysProject.setCreaterId(userId);
                sysProject.setUpdateId(userId);
                // 项目前缀（年月+序号）
                String ym = DateUtils.parseDateToStr("yyyyMM", new Date());
                // 查询最大数值
                String proPrex = sysProjectService.getProPrex(ym);
                if (StringUtils.isEmpty(proPrex)) {
                    sysProject.setProPrex(ym+"01");
                } else {
                    sysProject.setProPrex(proPrex);
                }
                sysProject.setIncludeSystemHistory(sysProject.getIncludeSystem());
                sysProjectService.save(sysProject);
                for (String includeSystemSg : sysProject.getIncludeSystem().split(",")) {
                    addSystemCode.add(includeSystemSg);
                }
            } else {
                SysProject updateInfo = sysProjectService.getById(sysProject.getId());
                //增加项目前缀
                if(null != updateInfo){
                    sysProject.setProPrex(updateInfo.getProPrex());
                }

                String includeSystemHistoryOld = updateInfo.getIncludeSystemHistory();
                if (StringUtils.isEmpty(includeSystemHistoryOld)) {
                    for (String includeSystemSg : sysProject.getIncludeSystem().split(",")) {
                        addSystemCode.add(includeSystemSg);
                    }
                    sysProject.setIncludeSystemHistory(sysProject.getIncludeSystem());
                } else {
                    // 不为空，取新增的部分，并把新增的部分更新到历史字段里面
                    ArrayList<String> includeSystemHistoryLs = new ArrayList<>(Arrays.asList(includeSystemHistoryOld.split(",")));
                    if (includeSystemHistoryLs.contains(Constants.AQGLXT) || includeSystemHistoryLs.contains(Constants.RYGLXT)
                    || includeSystemHistoryLs.contains(Constants.SBGLXT) || includeSystemHistoryLs.contains(Constants.LWGLXT)) {
                        zhgdCreateTable = false;
                    }
                    for (String includeSystemSg : sysProject.getIncludeSystem().split(",")) {
                        if (!includeSystemHistoryLs.contains(includeSystemSg)) {
                            addSystemCode.add(includeSystemSg);
                            includeSystemHistoryLs.add(includeSystemSg);
                        }
                    }
                    sysProject.setIncludeSystemHistory(StringUtils.join(includeSystemHistoryLs.toArray(), ","));
                }
                BeanUtils.copyPropertiesIgnoreNull(sysProject, updateInfo);
                updateInfo.setUpdateId(userId);
                updateInfo.setUpdateTime(new Date());
                sysProjectService.updateById(updateInfo);
            }
            // 根据项目包含哪些系统，来调用各个应用的接口，用于初始化表结构和字典数据
            ExecutorService executorService = Executors.newCachedThreadPool();

            executorService.shutdown();
            try {
                executorService.awaitTermination(1, TimeUnit.DAYS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        // 判断该租户是否已存在超管角色，不存在的话新增角色，命名为ROLE_SUPER_租户编码
        String roleCode = "ROLE_SUPER_" + sysTenant.getTenantCode();
        SysRole sysRole = sysRoleService.getByCode(roleCode);
        if (null == sysRole) {
            // 插入新角色
            sysRole = new SysRole();
            sysRole.setRoleName(sysTenant.getTenantName() + "超管角色");
            sysRole.setRoleCode(roleCode);
            sysRole.setRoleType("1");
            sysRole.setSort(0);
            sysRole.setCreaterId(userId);
            sysRole.setCreateTime(new Date());
            sysRole.setUpdateId(userId);
            sysRole.setUpdateTime(new Date());
            sysRoleService.save(sysRole);
            // 绑定角色和租户的关系
            sysRoleTenantService.inSertData(sysTenant.getTenantCode(), sysRole.getId(), userId);
        }
        // 处理超管，绑定超管和角色的关系
        // 需处理本身，向上处理，向下处理
        // 处理本身
        if (StringUtils.isNotEmpty(sysTenant.getTenantSuperAccount())) {
            // 插入角色
            sysRoleUserService.insertData(sysTenant.getTenantSuperAccount(), sysRole.getId(), userId);
        }
        // 向上处理
        if (StringUtils.isNotEmpty(sysTenant.getParentTenantCode())) {
            // 绑定父节点的超管账号和角色id
            bindParentAccount(sysTenant.getParentTenantCode(), sysRole.getId(), userId);
        }
        // 向下处理
        if (StringUtils.isNotEmpty(sysTenant.getTenantSuperAccount())) {
            bindChildAccount(sysTenant.getTenantCode(), sysTenant.getTenantSuperAccount(), userId);
        }

        // 判断该数据在组织表是否已存在，已存在就更新，不存在新增
        SysOrg sysOrg = sysOrgService.getInfoByOrgCode(sysTenant.getTenantCode(), sysTenant.getTenantCode());
        SysOrg orgInsert = new SysOrg();
        orgInsert.setOrgCode(sysTenant.getTenantCode());
        orgInsert.setOrgName(sysTenant.getTenantName());
        orgInsert.setOrgNuitName(sysTenant.getTenantName());
        orgInsert.setSort(0);
        orgInsert.setTenantCode(sysTenant.getTenantCode());
        if ("3".equals(sysTenant.getTenantTypeValue())) {
            orgInsert.setOrgTypeValue("4");
        } else {
            orgInsert.setOrgTypeValue(sysTenant.getTenantTypeValue());
        }
        orgInsert.setParentOrgCode(sysTenant.getParentTenantCode());
        if (null != sysOrg) {
            orgInsert.setId(sysOrg.getId());
        }
        ResultBean<JSONObject> resultBean = sysOrgService.saveOrUpdateData(orgInsert);
        if (201 == resultBean.getCode()) {
            return resultBean;
        }
        // 绑定角色和组织的关系
        sysRoleOrgService.insertData(orgInsert.getId(), sysRole.getId(), userId);
        return new ResultBean<>().success("处理成功！");
    }

    private void bindChildAccount(String tenantCode, String tenantSuperAccount, String userId) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled, 0);
        queryWrapper.eq(SysTenant::getParentTenantCode, tenantCode);
        List<SysTenant> sysTenants = baseMapper.selectList(queryWrapper);
        for (SysTenant sysTenant : sysTenants) {
            String roleCode = "ROLE_SUPER_" + sysTenant.getTenantCode();
            SysRole sysRole = sysRoleService.getByCode(roleCode);
            if (null == sysRole) {
                // 插入新角色
                sysRole = new SysRole();
                sysRole.setRoleName(sysTenant.getTenantName() + "超管角色");
                sysRole.setRoleCode(roleCode);
                sysRole.setRoleType("1");
                sysRole.setSort(0);
                sysRole.setCreaterId(userId);
                sysRole.setCreateTime(new Date());
                sysRole.setUpdateId(userId);
                sysRole.setUpdateTime(new Date());
                sysRoleService.save(sysRole);
            }
            sysRoleUserService.insertData(tenantSuperAccount, sysRole.getId(), userId);
        }
    }

    private void bindParentAccount(String parentTenantCode, String roleId, String userId) {
        SysTenant sysTenant = this.getByTenantCode(parentTenantCode);
        if (null != sysTenant) {
            if (StringUtils.isNotEmpty(sysTenant.getTenantSuperAccount())) {
                // 插入角色
                sysRoleUserService.insertData(sysTenant.getTenantSuperAccount(), roleId, userId);
            }
            if (StringUtils.isNotEmpty(sysTenant.getParentTenantCode())) {
                // 绑定父节点的超管账号和角色id
                bindParentAccount(sysTenant.getParentTenantCode(), roleId, userId);
            }
        }
    }

    @Override
    public SysTenant getDetail(String id) {
        SysTenant sysTenant = baseMapper.selectById(id);
        // 字典数据处理
        if (StringUtils.isNotEmpty(sysTenant.getTenantTypeValue())) {
            sysTenant.setTenantTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.TENANTTYPE.getCode(), sysTenant.getTenantTypeValue()));
        }
        if (StringUtils.isNotEmpty(sysTenant.getTenantSuperAccount())) {
            SysUser sysUser1 = sysUserService.getById(sysTenant.getTenantSuperAccount());
            if (null != sysUser1) {
                sysTenant.setTenantSuperAccountDesc(sysUser1.getUserName());
            }
        }
        sysTenant.setUpdateTimeStr(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, sysTenant.getUpdateTime()));
        SysUser sysUser = sysUserService.getById(sysTenant.getUpdateId());
        if (null != sysUser) {
            sysTenant.setUpdateName(sysUser.getUserName());
        }

        // 如果是项目，需查询项目数据
        if ("3".equals(sysTenant.getTenantTypeValue())) {
            SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(sysTenant.getTenantCode());
            if (null != sysProject.getProType()) {
                sysProject.setProTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.PROJECTTYPE.getCode(), sysProject.getProType().toString()));
            }
            if (null != sysProject.getRoadType()) {
                sysProject.setRoadTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ROADTYPE.getCode(), sysProject.getRoadType().toString()));
            }
            if (null != sysProject.getEngType()) {
                sysProject.setEngTypeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ENGINEERINGTYPE.getCode(), sysProject.getEngType().toString()));
            }
            if (null != sysProject.getRoadGrade()) {
                sysProject.setRoadGradeDesc(sysDictDataService.selectDictDescByKeyAndValue(ConfigDictTypeEnum.ROADGRADE.getCode(), sysProject.getRoadGrade().toString()));
            }
            if (StringUtils.isNotEmpty(sysProject.getProImage())) {
                SysFile sysFile = sysFileService.getFilePath(sysProject.getProImage());
                if (null != sysFile){
                    sysProject.setFilepath(sysFile.getFileUrl());
                }
            }
            sysTenant.setSysProject(sysProject);
        }
        return sysTenant;
    }

    @Override
    public ResultBean<JSONObject> deleteData(String id) {
        SysTenant sysTenant = baseMapper.selectById(id);
        // 只有子节点可以删除
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled,0);
        queryWrapper.eq(SysTenant::getParentTenantCode, sysTenant.getTenantCode());
        queryWrapper.last(" limit 1");
        List<SysTenant> child = baseMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(child)) {
            return new ResultBean<>().build("当前节点非子节点，无法删除！");
        }
        // 绑定菜单，如果已绑定，不可删除
        LambdaQueryWrapper<SysTenantPermission> stpWrapper = new LambdaQueryWrapper<>();
        stpWrapper.eq(SysTenantPermission::getDisabled,0);
        stpWrapper.eq(SysTenantPermission::getTenantCode, sysTenant.getTenantCode());
        stpWrapper.last(" limit 1");
        List<SysTenantPermission> sysTenantPermissions = sysTenantPermissionService.list(stpWrapper);
        if (!CollectionUtils.isEmpty(sysTenantPermissions)) {
            return new ResultBean<>().build("该项目已绑定菜单，无法删除！");
        }
        sysTenant.setDisabled(1);
        String userId = RequestHeaderUtils.getUserId(request);
        sysTenant.setUpdateId(userId);
        sysTenant.setUpdateTime(new Date());
        baseMapper.updateById(sysTenant);
        // 删除项目
        if ("3".equals(sysTenant.getTenantTypeValue())) {
            SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(sysTenant.getTenantCode());
            sysProject.setDisabled(1);
            sysProject.setUpdateId(userId);
            sysProject.setUpdateTime(new Date());
            sysProjectService.updateById(sysProject);
        }
        return new ResultBean<>().success("处理成功！");
    }

    @Override
    public List<SysTenant> getAllTenant() {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled,0);
        queryWrapper.select(SysTenant::getTenantCode, SysTenant::getTenantName);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<SysTenant> getTenantInfoMul(List<String> tenantCodeLs) {
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled,0);
        queryWrapper.in(SysTenant::getTenantCode, tenantCodeLs);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<SysTenant> getCopyTenant(String inParam) {
        // 如果时候超级管理员，查所有，否则，只查询自己有权限的租户
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = sysUserService.getById(userId);

        JSONObject object = JSONObject.parseObject(inParam);
        String tenantName = object.getString("tenantName");
        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled,0);
        // 如果租户名称是空的，查树，否则，查列表
        if (StringUtils.isEmpty(tenantName)) {
            if ("0".equals(sysUser.getIsStatus())) {
                queryWrapper.isNull(SysTenant::getParentTenantCode);
            }
        } else {
            queryWrapper.like(SysTenant::getTenantName, tenantName);
        }
        queryWrapper.orderByDesc(SysTenant::getCreateTime);
        List<String> tenantCodeLs = new ArrayList<>();
        if (!"0".equals(sysUser.getIsStatus())) {
            // 查询有权限的租户
            tenantCodeLs = baseMapper.selectQXTenantCode(userId);
            List<String> finalTenantCodeLs = tenantCodeLs;
            queryWrapper.and((wrapper)->{
                wrapper.notIn(SysTenant::getParentTenantCode, finalTenantCodeLs).or().isNull(SysTenant::getParentTenantCode);
            });
            queryWrapper.in(SysTenant::getTenantCode, tenantCodeLs);
        }
        List<SysTenant> list = baseMapper.selectList(queryWrapper);
        if (StringUtils.isEmpty(tenantName)) {
            for (SysTenant sysTenant : list) {
                List<SysTenant> child = getChildren(sysTenant.getTenantCode(), sysUser.getIsStatus(), tenantCodeLs);
                if (!CollectionUtils.isEmpty(child)) {
                    sysTenant.setChild(child);
                }
            }
        }
        return list;
    }

    @Override
    public List<SysTenant> getByUserIdPage(String userId) {
        List<SysTenant> ret = new ArrayList<>();
        List<SysTenant> list = baseMapper.getByUserIdPage(userId);

        // 构建树
        // 先查出所有的一级节点（没有父节点的都是）
        List<SysTenant> parentList = new ArrayList<>();
        for (SysTenant temp : list) {
            if (StringUtils.isEmpty(temp.getParentTenantCode())) {
                parentList.add(temp);
            } else {
                boolean flag = true;
                for (SysTenant temp1 : list) {
                    if (temp.getParentTenantCode().equals(temp1.getTenantCode())) {
                        flag = false;
                        break;
                    }
                }
                if (flag) {
                    parentList.add(temp);
                }
            }
        }
        for (SysTenant temp : parentList) {
            List<SysTenant> childs = getAllChildTenant(temp, list);
            temp.setChild(childs);
            ret.add(temp);
        }
        return ret;
    }

    @Override
    public List<SysTenant> getAllTenantQx(String userId, String roleId) {
        return baseMapper.getAllTenantQx(userId, roleId);
    }

    @Override
    public IPage<SysTenant> getProjectList(String inParam) {
        // 如果时候超级管理员，查所有，否则，只查询自己有权限的租户
        String userId = RequestHeaderUtils.getUserId(request);
        SysUser sysUser = sysUserService.getById(userId);

        JSONObject object = JSONObject.parseObject(inParam);
        String tenantName = object.getString("tenantName");

        LambdaQueryWrapper<SysTenant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTenant::getDisabled,0);
        // 如果租户名称是空的，查树，否则，查列表
        if (StringUtils.isEmpty(tenantName)) {

        } else {
            queryWrapper.like(SysTenant::getTenantName, tenantName);
        }
        queryWrapper.orderByDesc(SysTenant::getCreateTime);
        List<String> tenantCodeLs = new ArrayList<>();
        // 只查询有权限的租户或者是自己创建的租户

        tenantCodeLs = baseMapper.selectQXTenantCodeAndCreate(userId);
        List<String> finalTenantCodeLs = tenantCodeLs;
//        queryWrapper.and((wrapper)->{
//            wrapper.notIn(SysTenant::getParentTenantCode, finalTenantCodeLs).or().isNull(SysTenant::getParentTenantCode);
//        });
        queryWrapper.in(SysTenant::getTenantCode, tenantCodeLs);
        queryWrapper.eq(SysTenant::getTenantTypeValue,3);//只查项目

        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPage();
        Integer pageSize = pageDomain.getPageSize();
        Page<SysTenant> page = new Page<>(pageNum, pageSize);
        IPage<SysTenant> iPage = baseMapper.selectPage(page, queryWrapper);
        for (SysTenant sysTenant : iPage.getRecords()) {
            SysProject sysProject = sysProjectService.getProjectInfoByTenatCode(sysTenant.getTenantCode());
            if(null != sysProject){
                String includeSystem = sysProject.getIncludeSystem();
                if(StringUtils.isNotEmpty(includeSystem)){
                    String[] split = includeSystem.split(",");
                    StringJoiner stringJoiner = new StringJoiner(",");
                    for (String s : split) {
                        SysSystem sysSystem = sysSystemService.getOne(Wrappers.<SysSystem>lambdaQuery().eq(SysSystem::getSystemCode, s));
                        if(null != sysSystem){
                            stringJoiner.add(sysSystem.getSystemName());
                        }
                    }
                    sysTenant.setIncludeSystem(stringJoiner.toString());
                }
            }
            sysTenant.setSysProject(sysProject);
        }
        return iPage;
    }
}
